import { useState, useEffect } from 'react';
import { Form, message } from 'antd';
import { rolesApi } from '@/api/roles';
import { Role } from './types';

export function useRoleManagement() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [pagination, setPagination] = useState({ page: 1, limit: 10, total: 0 });
  const [searchParams, setSearchParams] = useState({});

  // 权限选项（可根据实际情况提取到外部或props）
  const permissionOptions = [
    { label: '用户查看', value: 'user:read' },
    { label: '用户编辑', value: 'user:write' },
    { label: '角色查看', value: 'role:read' },
    { label: '角色编辑', value: 'role:write' },
    { label: '部门查看', value: 'department:read' },
    { label: '部门编辑', value: 'department:write' },
  ];

  // 获取角色列表
  const fetchRoles = async (params = {}) => {
    setLoading(true);
    try {
      const query = { page: pagination.page, limit: pagination.limit, ...searchParams, ...params };
      const res = await rolesApi.getRoles(query);
      setRoles(res.roles || res.list || []);
      setPagination({
        page: res.pagination?.page || 1,
        limit: res.pagination?.limit || 10,
        total: res.pagination?.total || res.total || 0,
      });
    } catch (error) {
      message.error('获取角色列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRoles();
    // eslint-disable-next-line
  }, [pagination.page, pagination.limit, searchParams]);

  // 查询
  const handleQuery = async (values: any) => {
    setLoading(true);
    setSearchParams(values);
    setPagination((p) => ({ ...p, page: 1 }));
    await fetchRoles({ ...values, page: 1 });
    setLoading(false);
  };

  // 重置
  const handleReset = async () => {
    setLoading(true);
    searchForm.resetFields();
    setSearchParams({});
    setPagination((p) => ({ ...p, page: 1 }));
    await fetchRoles({ page: 1 });
    setLoading(false);
  };

  // 分页变更
  const handleTableChange = (paginationInfo: any) => {
    setPagination({
      ...pagination,
      page: paginationInfo.current,
      limit: paginationInfo.pageSize,
    });
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      if (editingRole) {
        await rolesApi.updateRole(editingRole.id, values);
        message.success('角色更新成功');
      } else {
        await rolesApi.createRole(values);
        message.success('角色创建成功');
      }
      setModalVisible(false);
      form.resetFields();
      setEditingRole(null);
      fetchRoles();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除
  const handleDelete = async (id: number) => {
    try {
      await rolesApi.deleteRole(id);
      message.success('删除成功');
      fetchRoles();
    } catch (error) {
      message.error('删除失败');
    }
  };

  return {
    roles,
    loading,
    modalVisible,
    editingRole,
    form,
    searchForm,
    pagination,
    setModalVisible,
    setEditingRole,
    fetchRoles,
    handleSubmit,
    handleDelete,
    handleQuery,
    handleReset,
    handleTableChange,
    permissionOptions,
  };
} 